package com.example.toy.core.table;

import lombok.Getter;

import java.util.Optional;

@Getter
public class TableIdentifier {

  private final Optional<String> catalog;
  private final Optional<String> database;
  private final String table;

  public static TableIdentifier of(String identifierName) {
    String[] split = identifierName.split("\\.");
    if (split.length == 1) {
      return new TableIdentifier(split[0]);
    } else if (split.length == 2) {
      return new TableIdentifier(Optional.empty(), Optional.of(split[0]), split[1]);
    } else if (split.length == 3) {
      return new TableIdentifier(Optional.of(split[0]), Optional.of(split[1]), split[2]);
    } else {
      throw new IllegalStateException(
              "Can not analyze table identifier from string: " + identifierName);
    }
  }


  public TableIdentifier(Optional<String> catalog, Optional<String> database, String table) {
    this.catalog = catalog;
    this.database = database;
    this.table = table;
  }

  public TableIdentifier(String table) {
    this(Optional.empty(), Optional.empty(), table);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    if (catalog.isPresent()) {
      sb.append(catalog.get()).append(".");
    }
    if (database.isPresent()) {
      sb.append(database.get()).append(".");
    }
    sb.append(table);
    return sb.toString();
  }
}
